package com.miracle.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class MyJdbcTemplate {
	private String className;
	private String url;
	private String user;
	private String password;
	
	public Connection getConnection() {
		return getConnection(className, url, user, password);
	}
	
	public Connection getConnection(String className, String url, String user, String password) {
		try {
			Class.forName(className);
			Connection conn = DriverManager.getConnection(url, user, password);
			return conn;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public <T> T execute(ConnectionCallback<T> action) throws SQLException {
		Connection conn = getConnection();
		try {
			return action.doInConnection(conn);
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if(conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					// egnore
					e.printStackTrace();
				}
				conn = null;
			}
		}
	}

	/**
	 * @return the className
	 */
	public String getClassName() {
		return className;
	}

	/**
	 * @param className the className to set
	 */
	public void setClassName(String className) {
		this.className = className;
	}

	/**
	 * @return the url
	 */
	public String getUrl() {
		return url;
	}

	/**
	 * @param url the url to set
	 */
	public void setUrl(String url) {
		this.url = url;
	}

	/**
	 * @return the user
	 */
	public String getUser() {
		return user;
	}

	/**
	 * @param user the user to set
	 */
	public void setUser(String user) {
		this.user = user;
	}

	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @param password the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}
	
}
